/**
 * 封装get请求
 * 技术栈:function + ajax + promise
 * @param {String} url 
 * @param {Object} params 
 * @param {String|undefined} type 
 * @param {Object} headers 
 * @returns Promise
 */
function get(url, params, type, headers) { 
    const p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    if (type === 'json') res = JSON.parse(res)
                    resolve(res)
                } else {
                    //console.log('瑕疵:', xhr.status)
                    reject(xhr.status)
                }
            }
        }
        let temp = []
        for (let key in params) {
            temp.push(`${key}=${params[key]}`)
        }
        let paramsFilter = temp.join('&')
        xhr.open('get', `${url}?${paramsFilter}`)
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key])
        }
        xhr.send(null)
    })
    return p
}

/**
 * 封装post请求
 * 技术栈:function + ajax + promise
 * @param {String} url 
 * @param {Object} params 
 * @param {String|undefined} type 
 * @param {Object} headers 
 * @returns Promise
 */
function post(url, params, type, headers) {
    const p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    if (type === 'json') res = JSON.parse(res)
                    resolve(res)
                } else {
                    //console.log('瑕疵:', xhr.status)
                    reject(xhr.status)
                }
            }
        }
        let temp = []
        for (let key in params) {
            temp.push(`${key}=${params[key]}`)
        }
        let paramsFilter = temp.join('&')
        xhr.open('post', url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key])
        }
        xhr.send(paramsFilter)
    })
    return p
}